Imports System.Xml.Serialization
Imports AppliedRecognition.Speech.QuickSwitch.serialization
Imports System.IO
Imports System.ComponentModel
Imports Microsoft.Win32
Imports AppliedRecognition.Util
Imports System.Text.RegularExpressions

Public Class QuickSwitchConfig

    Public Event ShowSystrayChanged()

#Region "Config Setup"

    Friend SpeechCommandFile As String = "SpeechCommands.xml"


    Public Sub New(Optional ByVal emergencyExceptionMode As Boolean = False)
        Dim sp As String = Application.StartupPath

    End Sub
#End Region



#Region "Non ini properties"

    Const rkStartup As String = "Software\Microsoft\Windows\CurrentVersion\Run"
    Public Property RunAtStartup() As Boolean
        Get
            Dim runRK As RegistryKey = Registry.CurrentUser.OpenSubKey(rkStartup)
            If runRK Is Nothing Then Return False
            Dim runs As String = runRK.GetValue("QuickSwitch", "").ToString
            If runs = Application.ExecutablePath Then Return True
            Return False
        End Get
        Set(ByVal Value As Boolean)
            Dim runRK As RegistryKey = Registry.CurrentUser.OpenSubKey(rkStartup, True)
            If Value = False Then
                runRK.DeleteValue("QuickSwitch", False)
            Else
                runRK.SetValue("QuickSwitch", Application.ExecutablePath)
            End If
            runRK.Close()
        End Set
    End Property

    Public ReadOnly Property TraceLogFile() As String
        Get
            Return IO.Path.Combine(Me.DebugDataPath, LogFileName)
        End Get
    End Property

    Public ReadOnly Property LogFileName() As String
        Get
            If TraceLogFileNameAttemptCount = 0 Then
                Return "Trace.log"
            End If
            Return "Trace" + TraceLogFileNameAttemptCount.ToString + ".log"
        End Get
    End Property


    Private _debugdatapath As String
    Public ReadOnly Property DebugDataPath() As String
        Get
            If _debugdatapath = "" Then
                Dim p As String = (IO.Path.Combine(DataPath, "Debug"))
                IO.Directory.CreateDirectory(p)
                _debugdatapath = p
            End If
            Return _debugdatapath
        End Get
    End Property

    Private _datapath As String
    Public Property DataPath() As String
        Get
            If _datapath = "" Then

                Dim company As String = My.Application.Info.CompanyName.Replace(".", "")
                Dim luadp As String = IO.Path.Combine( _
                IO.Path.Combine( _
                                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), _
                                company), _
                            My.Application.Info.ProductName)

                _datapath = luadp
            End If
            Return _datapath
        End Get
        Set(ByVal Value As String)
            _datapath = Value
        End Set
    End Property


    Private _numfont As Font
    <Browsable(False)> _
        Public ReadOnly Property NumFont() As Font
        Get
            If _numfont Is Nothing Then
                _numfont = New Font(My.MySettings.Default.NumFontFamily, My.MySettings.Default.NumFontSize)
            End If
            Return _numfont
        End Get
    End Property

    Private _textfont As Font
    <Browsable(False)> _
        Public ReadOnly Property TextFont() As Font
        Get
            If _textfont Is Nothing Then
                _textfont = New Font(My.MySettings.Default.NumFontFamily, My.MySettings.Default.NumFontSize - 3)
            End If
            Return _textfont
        End Get
    End Property


    Private _SpeechConfig As SpeechCommandSet
    <Browsable(False)> _
        Public ReadOnly Property SpeechConfig() As SpeechCommandSet

        Get
            Dim tr As IO.TextReader = Nothing
            Try
                If _SpeechConfig Is Nothing Then
                    Dim xser As New XmlSerializer(GetType(SpeechCommandSet))
                    tr = SpeechCommandsDocumentReader
                    _SpeechConfig = DirectCast(xser.Deserialize(tr), SpeechCommandSet)
                    If _SpeechConfig.Version <> "1.1" Then
                        Throw New QuickSwitchInvalidConfigFileException("Speech commands are out of date")
                    End If
                End If
                Return _SpeechConfig
            Catch ex As InvalidOperationException
                Trace.WriteLine(ex.ToString)
                Throw New QuickSwitchInvalidConfigFileException("Speech commands file is invalid.")
            Finally
                If Not tr Is Nothing Then
                    tr.Close()
                End If
            End Try
        End Get
    End Property

    Friend ReadOnly Property HelpXSLT() As Xml.XmlReader
        Get
            Dim s As Stream = GetType(QSRes).Assembly.GetManifestResourceStream("QSRes.Help.xslt")
            Dim xr As New Xml.XmlTextReader(s)
            Return xr
        End Get
    End Property
    Friend ReadOnly Property SpeechCommandsDocumentReader() As IO.TextReader
        Get
            Dim fs As StreamReader
            Dim paths(1) As String
            paths(0) = Path.Combine(DataPath, SpeechCommandFile)
            paths(1) = Path.Combine(Application.StartupPath, SpeechCommandFile)

            Dim f As String
            For Each f In paths
                If File.Exists(f) Then
                    fs = New IO.StreamReader(f)
                    Return fs
                End If
            Next

            fs = New StreamReader(GetType(QSRes).Assembly.GetManifestResourceStream("QSRes." + SpeechCommandFile))
            Return fs

            Throw New FileNotFoundException("Unable to find speech command file. Please repair installation.", SpeechCommandFile)

        End Get
    End Property
    Friend ReadOnly Property SpeechCommandsXPathDoc() As Xml.XPath.XPathDocument
        Get
            Return New Xml.XPath.XPathDocument(SpeechCommandsDocumentReader)
        End Get
    End Property
    Private Shared secGuid As New Guid("{E205F95F-E5DD-499b-9673-F68D8B1CFDB5}")
    Friend Shared ReadOnly Property SecurityGuid() As Guid
        Get
            Return secGuid
        End Get
    End Property
    Public Shared ReadOnly Property RegUserDataPath() As String
        Get
            Return "Software\" + Application.CompanyName + "\" + Application.ProductName
        End Get
    End Property
    Friend Shared Property CustomerEmail() As String
        Get
            Dim rk As RegistryKey = Registry.CurrentUser.OpenSubKey(RegUserDataPath, False)
            If rk Is Nothing Then Return ""
            Dim ce As String = CStr(rk.GetValue("CustomerEmail", ""))
            rk.Close()
            Return ce
        End Get
        Set(ByVal Value As String)
            Dim rk As RegistryKey = Registry.CurrentUser.CreateSubKey(RegUserDataPath)
            rk.SetValue("CustomerEmail", Value)
            rk.Close()
        End Set
    End Property
    Friend Shared Property CustomerName() As String
        Get
            Dim rk As RegistryKey = Registry.CurrentUser.OpenSubKey(RegUserDataPath, False)
            If rk Is Nothing Then Return ""
            Dim ce As String = CStr(rk.GetValue("CustomerName", ""))
            rk.Close()
            If ce = "" Then
                ce = Util.UnhandledExceptionManager.UserIdentity
            End If
            Return ce
        End Get
        Set(ByVal Value As String)
            Dim rk As RegistryKey = Registry.CurrentUser.CreateSubKey(RegUserDataPath)
            rk.SetValue("CustomerName", Value)
            rk.Close()
        End Set
    End Property
#End Region


    Private Shared snCheckRE As New Regex("^QSComplete", RegexOptions.Compiled)

    Private Shared TraceLogFileNameAttemptCount As Integer
    Private Sub UpdateTraceLogFileName()
        TraceLogFileNameAttemptCount += 1
    End Sub

    Private Shared traceSW As IO.StreamWriter
    Private Shared traceListener As TextWriterTraceListener
    Public Sub EnableTracing()
        If traceSW Is Nothing Then
            Dim fi As New FileInfo(TraceLogFile)
            If fi.Exists AndAlso fi.Length >= (1024 * 300) Then
                Try
                    fi.Delete()
                Catch ex As Exception
                End Try
            End If

            For ii As Integer = 0 To 9
                Try
                    traceSW = New IO.StreamWriter(Me.TraceLogFile, True)
                    If Not traceSW Is Nothing Then Exit For
                Catch ex As Exception
                    UpdateTraceLogFileName()
                End Try
            Next
            If traceSW Is Nothing Then
                MessageBox.Show("Unable to create file Trace.log. Please ensure you have access to " + DebugDataPath, "QuickSwitch Error")
                Application.Exit()
            End If

            traceListener = New TextWriterTraceListener(traceSW)
            traceListener.Name = "QSTrace"
            Trace.Listeners.Add(traceListener)
        End If
    End Sub

    Public Sub DisableTracing()
        If traceSW Is Nothing Then Exit Sub
        Trace.Flush()
        traceListener.Close()
        Trace.Listeners.Remove(traceListener)
        traceSW.Close()
        traceSW = Nothing
    End Sub

End Class
